import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/member_service.dart';
import 'package:flutter_oldman_health/models/distance_limit_model.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/edit_dialog.dart';

import 'map_address_select_page.dart';

class MapSettingPage extends StatefulWidget {
  FamilyRelationItem relationItem;
  int rangeNum = 1000;
  DistanceLimitItem distanceLimitItem;

  MapSettingPage(this.distanceLimitItem, this.relationItem) {
    if (distanceLimitItem != null) rangeNum = distanceLimitItem.distance;
  }

  @override
  MapSettingPageState createState() {
    return MapSettingPageState();
  }
}

class MapSettingPageState extends State<MapSettingPage> {
  int customNum = -1;
  Size screenSize;
  List rangeList = [1000, 1500, 2000, 2500];
  String selectAddress = "请点击选择区域坐标";
  BMFCoordinate selectGeoPt;
  bool _openAreaProtectionWarning = false;

  @override
  void initState() {
    super.initState();
    _openAreaProtectionWarning = widget.distanceLimitItem.remind == 1;
    print(_openAreaProtectionWarning);

    // Utils.getBoolSharePreferences("area_protection_warning").then((value) {
    //   setState(() {
    //     print(_openAreaProtectionWarning);
    //     _openAreaProtectionWarning = value;
    //     print(_openAreaProtectionWarning);
    //   });
    // });
    if (null != widget.rangeNum && !rangeList.contains(widget.rangeNum)) {
      customNum = widget.rangeNum;
    }
    if (widget.distanceLimitItem != null) {
      selectGeoPt = BMFCoordinate(widget.distanceLimitItem.latitude,
          widget.distanceLimitItem.longitude);
    }
    if (widget.distanceLimitItem.id != null) {
      print("distanceLimitItem ${widget.distanceLimitItem.id}");

      selectAddress =
          "${widget.distanceLimitItem.latitude} ${widget.distanceLimitItem.longitude}";
    }
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;

    return MaterialApp(
        home: Scaffold(
            body: WillPopScope(
                onWillPop: () async {
                  Navigator.pop(context);
                  // myMapController.removeMarker(marker);
                  return false;
                },
                child: Container(
                    color: Constant.backgroundColor,
                    child: Column(
                      children: [
                        _getTitle(),
                        Image.asset('images/ic_family_member_head.png',
                            width: 60, height: 60),
                        Container(
                          margin: EdgeInsets.all(12),
                          child: Text(
                            widget.relationItem.alias,
                            style: TextStyle(fontSize: 17),
                          ),
                        ),
                        Container(height: 1, color: Color(0xffdddddd)),
                        Container(
                            padding:
                                EdgeInsets.only(left: 16, top: 8, bottom: 8),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              "区域坐标",
                              style: TextStyle(fontSize: 17),
                            )),
                        GestureDetector(
                            behavior: HitTestBehavior.translucent,
                            onTap: () async {
                              BMFCoordinate data = await Navigator.push(context,
                                  MaterialPageRoute(builder: (context) {
                                return MapAddressSelectPage(selectGeoPt);
                              }));
                              if (data != null) {
                                print("selectGeoPt222.longitude");
                                print("${data.latitude}  ${data.longitude}");
                                selectAddress =
                                    "${data.latitude}  ${data.longitude}";
                                print("selectAddress :   $selectAddress");

                                if (selectGeoPt != null)
                                  print(selectGeoPt.longitude);
                                setState(() {
                                  selectGeoPt = data;
                                  print(selectGeoPt.longitude);
                                  selectAddress =
                                      "${data.latitude}  ${data.longitude}";
                                });
                              }
                            },
                            child: Container(
                                alignment: Alignment.center,
                                child: Text(selectAddress,
                                    style: TextStyle(
                                        color: Color(0xff888888),
                                        fontSize: 17)))),
                        Container(
                            padding: EdgeInsets.only(left: 16, top: 8),
                            alignment: Alignment.centerLeft,
                            child:
                                Text("区域范围", style: TextStyle(fontSize: 17))),
                        Wrap(children: _getRangeWidgetList()),
                        Container(
                            padding:
                                EdgeInsets.only(left: 16, bottom: 8, right: 16),
                            alignment: Alignment.centerLeft,
                            child: Row(
                              children: [
                                Expanded(
                                    flex: 1,
                                    child: Text(
                                        _openAreaProtectionWarning
                                            ? "已打开防护区域警告"
                                            : "已关闭防护区域警告",
                                        style: TextStyle(fontSize: 17))),
                                Switch(
                                    activeColor: Colors.orangeAccent,
                                    value: _openAreaProtectionWarning,
                                    onChanged: (v) {
                                      print(
                                          "_openAreaProtectionWarning $_openAreaProtectionWarning");
                                      setState(() {
                                        _openAreaProtectionWarning = v;
                                      });
                                    })
                              ],
                            )),
                        Container(
                            margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
                            padding: EdgeInsets.all(12),
                            child: GestureDetector(
                                behavior: HitTestBehavior.translucent,
                                onTap: () {
                                  if (null == selectGeoPt ||
                                      selectAddress.contains("点击")) {
                                    EasyLoading.showInfo("请选择区域坐标");
                                    return;
                                  }
                                  createDistanceLimit();
                                },
                                child: FractionallySizedBox(
                                    widthFactor: 1,
                                    child: Text("确认",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                            fontSize: 17,
                                            color: Colors.white)))),
                            decoration: BoxDecoration(
                                border: Border.all(
                                    color: Color(0xFFEEEEEE), width: 1),
                                color: Colors.orangeAccent,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(58)))),
                        if (null != widget.distanceLimitItem.id)
                          Container(
                              margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
                              padding: EdgeInsets.all(12),
                              child: GestureDetector(
                                  behavior: HitTestBehavior.translucent,
                                  onTap: () async {
                                    showRemindDialog(
                                        context, deleteDistanceLimit);
                                    //deleteDistanceLimit();
                                  },
                                  child: FractionallySizedBox(
                                      widthFactor: 1,
                                      child: Text("删除",
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 17,
                                              color: Colors.white)))),
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Color(0xFFEEEEEE), width: 1),
                                  color: Colors.red,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(58))))
                      ],
                    )))));
  }

  List<Widget> _getRangeWidgetList() {
    List<Widget> widgetList = [];
    var widgetList2 = rangeList.map((e) => _getRangeWidget(e)).toList();
    widgetList.addAll(widgetList2);
    widgetList.add(_getCustomRangeWidget());
    if (customNum > 0) {
      TextEditingController controller = TextEditingController();
      controller.text = customNum.toString();
      widgetList.add(Stack(
        children: [
          Container(
              width: screenSize.width / 4,
              height: 40,
              padding: EdgeInsets.only(left: 16),
              child: TextField(
                  controller: controller,
                  readOnly: true,
                  autofocus: false,
                  decoration: InputDecoration(
                      // hintText: remarksName,
                      hintStyle: TextStyle(fontSize: 18),
                      //重点 修改下划线
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Color(0xaa41BAB0))),
                      enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Color(0xff41BAB0)))
                      //InputBorder.none  OutlineInputBorder() ///border: OutlineInputBorder()
                      ))),
          GestureDetector(
              onTap: () async {
                String num = await showDialog(
                    context: context,
                    builder: (context) =>
                        CustomEditDialog("自定义范围", customNum, type: 2));
                if (null == num) {
                  //customNum = -1;
                } else if (num.length > 0) {
                  customNum = int.parse(num);
                  setState(() {
                    widget.rangeNum = customNum;
                  });
                }
              },
              child: Container(
                  color: Colors.transparent,
                  width: screenSize.width / 4,
                  height: 40,
                  padding: EdgeInsets.only(left: 16)))
        ],
      ));
    }
    return widgetList;
  }

  Widget _getCustomRangeWidget() {
    return Container(
        width: screenSize.width / 3,
        child: Row(children: [
          Radio(
              activeColor: Colors.orangeAccent,
              groupValue: widget.rangeNum,
              value: customNum,
              onChanged: (check) {
                if (customNum == -1) {
                  showDialog(
                          context: context,
                          builder: (context) =>
                              CustomEditDialog("自定义范围", customNum, type: 2))
                      .then((value) {
                    if (null == value) {
                      //customNum = -1;
                    } else if (value.length > 0) {
                      setState(() {
                        customNum = int.parse(value);
                        widget.rangeNum = customNum;
                      });
                    }
                  });
                } else {
                  setState(() {
                    widget.rangeNum = customNum;
                  });
                }
              }),
          GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () async {
                if (customNum == -1 || widget.rangeNum == customNum) {
                  String num = await showDialog(
                      context: context,
                      builder: (context) =>
                          CustomEditDialog("自定义范围", customNum, type: 2));
                  if (null == num) {
                    //customNum = -1;
                  } else if (num.length > 0) {
                    customNum = int.parse(num);
                    setState(() {
                      widget.rangeNum = customNum;
                    });
                  }
                } else {
                  setState(() {
                    widget.rangeNum = customNum;
                  });
                }
              },
              child: Text("自定义")),
        ]));
  }

  Widget _getRangeWidget(int range) {
    return Container(
        width: screenSize.width / 3,
        child: Row(
          children: [
            Radio(
                activeColor: Colors.orangeAccent,
                groupValue: widget.rangeNum,
                value: range,
                onChanged: (check) {
                  setState(() {
                    widget.rangeNum = range;
                  });
                }),
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  setState(() {
                    widget.rangeNum = range;
                  });
                },
                child: Text("$range米"))
          ],
        ));
  }

  Widget _getTitle([String title = "区域防护设置"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 4),
        margin: EdgeInsets.only(bottom: 16),
        child: FractionallySizedBox(
            widthFactor: 1,
            child: Stack(alignment: Alignment.center, children: [
              Positioned(
                  left: 2,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        Navigator.pop(context);
                        //myMapController.removeMarker(marker);
                      },
                      child: Container(
                          child: Icon(Icons.arrow_back_ios),
                          padding: EdgeInsets.fromLTRB(15, 10, 20, 10)))),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal))
            ])));
  }

  void createDistanceLimit() {
    if (widget.distanceLimitItem.id == null) {
      FamilyMemberService.createDistanceLimit(
              widget.relationItem.memberId,
              selectGeoPt.longitude,
              selectGeoPt.latitude,
              widget.rangeNum,
              _openAreaProtectionWarning ? 1 : 0)
          .then((value) {
        updateDistanceLimit(value);
      });
    } else {
      FamilyMemberService.updateDistanceLimit(
              widget.distanceLimitItem.id,
              widget.relationItem.memberId,
              selectGeoPt.longitude,
              selectGeoPt.latitude,
              widget.rangeNum,
              _openAreaProtectionWarning ? 1 : 0)
          .then((value) {
        updateDistanceLimit(value);
      });
    }
  }

  Future showRemindDialog(BuildContext context, Function() callback) async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: Text("删除区域防护"),
              content: Text("确定删除当前区域防护设置？"),
              actions: <Widget>[
                ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child:
                        Padding(padding: EdgeInsets.all(8), child: Text("取消")),
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(StadiumBorder(
                          side: BorderSide(
                              //设置 界面效果 圆角弧度
                              style: BorderStyle.solid,
                              color: Colors.grey[400]))),
                      foregroundColor:
                          MaterialStateProperty.all(Color(0xff333333)),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      textStyle:
                          MaterialStateProperty.all(TextStyle(fontSize: 17)),
                    )),
                ElevatedButton(
                    onPressed: () async {
                      // var callback2 = callback;
                      deleteDistanceLimit();
                    },
                    child:
                        Padding(padding: EdgeInsets.all(8), child: Text("确定")),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.orange),
                        textStyle:
                            MaterialStateProperty.all(TextStyle(fontSize: 17)),
                        shape: MaterialStateProperty.all(StadiumBorder(
                            side: BorderSide(
                          //设置 界面效果 圆角弧度
                          style: BorderStyle.solid,
                          color: Color(0xffFF7F24),
                        )))))
              ]);
        });
    return result;
  }

  void deleteDistanceLimit() {
    FamilyMemberService.deleteDistanceLimit(widget.distanceLimitItem.id)
        .then((value) {
      if (value != null && value.statusCode == 200) {
        ResponseDataModel<String> model =
            ResponseDataModel.fromJson(value.data);
        if (model.success()) {
          Utils.putIntSharePreferences("area_protection_distance", -1);
          Utils.putBoolSharePreferences(
              "area_protection_warning", _openAreaProtectionWarning);
          Navigator.pop(context);
          Navigator.pop(context);
        } else {
          EasyLoading.showInfo(model.msg);
        }
        return;
      }
      EasyLoading.showInfo("删除区域防护失败");
    });
  }

  void updateDistanceLimit(value) {
    if (value != null && value.statusCode == 200) {
      ResponseDataModel<String> model = ResponseDataModel.fromJson(value.data);
      if (model.success()) {
        Utils.putIntSharePreferences(
            "area_protection_distance", widget.rangeNum);
        Navigator.pop(context, selectGeoPt);
      } else {
        EasyLoading.showInfo(model.msg);
      }
      return;
    }
    EasyLoading.showInfo("添加区域防护失败");
  }
}
